package com.cdream.basic.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

/**
 * @author cdream
 * @date 2022/10/21
 */
@Slf4j
public class HelloClient {
    public static void main(String[] args) throws InterruptedException, IOException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        Channel channel = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                log.info(((ByteBuf)msg).toString(StandardCharsets.UTF_8));
                                super.channelRead(ctx, msg);
                            }
                        });
                    }
                })
                .connect(new InetSocketAddress("localhost", 9011))
                .sync()
                .channel();
        channel.writeAndFlush("男儿走四方，何处不为家\n");
        channel.writeAndFlush("天下何处不青山\n");
        channel.writeAndFlush("他化自在，他化万古\n");

        ChannelFuture future = channel.closeFuture();
        future.addListener((f)-> {
            log.info("我优雅的关闭了");
            group.shutdownGracefully();
        });
        // channel.close();
        while (true){
            BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
            String line = bf.readLine();
            // log.info(line);
            channel.writeAndFlush(line);
        }

    }
}
